package com.apes.framework.plugin.fsm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * @Title: FsmStateLogService
 * @Description: 状态机Log
 * @author: ZhengZeXian
 * @create: 2021/1/18 18:13
 */
@Service("fsmStateLogService")
@SuppressWarnings("all")
public class FsmStateLogService extends DomainService {

    @Autowired
    private FsmFlowInstanceRepository fsmFlowInstanceRepository;
    @Autowired
    private FsmStateInstanceRepository fsmStateInstanceRepository;
    @Autowired
    private FsmStateInstanceTaskRepository fsmStateInstanceTaskRepository;
    @Autowired
    private FsmTaskRepository fsmTaskRepository;

    /**
     * 查询状态Log
     * @param request
     * @return
     */
    public Map findAll(SimpleRequest request){
        //获取所有状态流按最后更新日期降序排列
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "UpdateDate");
//        List<FsmFlowInstance> fsmFlowInstances = fsmFlowInstanceRepository.findAll(sort);
        Page<FsmFlowInstance> fsmFlowInstances = fsmFlowInstanceRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
        List<Map> result = new ArrayList<Map>();
        if (!fsmFlowInstances.isEmpty()){
            fsmFlowInstances.stream().forEach(fsm -> {
                Map map = new HashMap();
                map.put("fsmFlow","["+fsm.getFsmFlow().getId()+"]"+fsm.getFsmFlow().getName());//状态流
                map.put("id",fsm.getId());  //状态流实例ID
                map.put("fsmState","["+fsm.getCurrentState().getId()+"]"+fsm.getCurrentState().getName());//状态
                map.put("updater","["+(fsm.getUpdater() == null ? "--" : findNameById(fsm.getUpdater())) +"]" + (fsm.getUpdateDate() == null ? "--" : fsm.getUpdateDate()));    //更新
                map.put("creator","["+(fsm.getCreator() == null ? "--" : findNameById(fsm.getCreator())) +"]"+ (fsm.getCreateDate() == null ? "--" : fsm.getCreateDate()));    //创建
                map.put("finished",fsm.isFinished() ? "1" : "0");   //结束
                map.put("suspend",fsm.isSuspend() ? "1" : "0"); //挂起
                map.put("business","["+fsm.getBusinessType().getName()+"]"+fsm.getBusinessKey());
                List<Map> stateList = new ArrayList<>();
                //查找对应状态按最后更新日期降序排序
                List<FsmStateInstance> fsmStateInstances = fsmStateInstanceRepository.findByFsmFlowInstanceIdOrderByUpdateDateDesc(fsm.getId());
                if (!fsmStateInstances.isEmpty() && fsmStateInstances!=null){
                    fsmStateInstances.stream().forEach(fsms -> {
                        Map temp = new HashMap();
                        temp.put("fsmState",fsms.getState() == null ? "--" : "["+fsms.getState().getId()+"]"+fsms.getState().getName());//状态
                        temp.put("id",fsms.getId());//状态实例ID
                        temp.put("fsmEvent",fsms.getEvent() == null ? "--" : "["+fsms.getEvent().getId()+"]"+fsms.getEvent().getName());//触发事件
                        temp.put("updater","["+(fsms.getUpdater() == null ? "--" : findNameById(fsms.getUpdater())) +"]" + (fsms.getUpdateDate() == null ? "--" : fsms.getUpdateDate()));    //更新
                        temp.put("creator","["+(fsms.getCreator() == null ? "--" : findNameById(fsms.getCreator())) +"]" + (fsms.getCreateDate() == null ? "--" : fsms.getCreateDate()));    //创建
                        temp.put("finished",fsms.isFinished() ? "1" : "0");   //结束
                        temp.put("innerBusiness","["+fsms.getFsmFlowInstance().getFsmFlow().getName()+"]"+fsms.getFsmFlowInstance().getId());   //来源单据
                        stateList.add(temp);
                    });
                }
                    map.put("detailList",stateList);
                result.add(map);
            });
        }
        return MapUtil.mapper(
                "content", result,
                "total", ((PageImpl)fsmFlowInstances).getTotalElements(),
                "size", result.size()
        );
    }

    /**
     * 获取 状态实例任务
     * @return
     */
    public Map getFsmStateInstanceTask(SimpleRequest request){
        JSONObject param = request.getJO();
        JSONObject data = param.getJSONObject("data"); // 表单数据
        JSONObject rowData = data.getJSONObject("node"); // 选中行
        String id = rowData.getString("id");
        if (id == null) id = rowData.getString("STATE_INST_ID");
        List<Map> temp = new ArrayList();
        //任务流按最后更新日期降序排序
        List<FsmStateInstanceTask> instanceTasks = fsmStateInstanceTaskRepository.findByFsmStateInstanceIdOrderByUpdateDateDesc(id);
        if (instanceTasks != null){
            instanceTasks.stream().forEach(instanceTask -> {
                FsmTask task = fsmTaskRepository.findOne(instanceTask.getTaskId());
                temp.add(MapUtil.mapper(
                        "id", task == null ? "--" : task.getId(),  //任务ID
                        "executed", formatExecuted(instanceTask.getParams()),   //执行参数
                        "times", instanceTask.getTimes(),  //执行次数
                        "userExpr", task == null ? "--" : task.getUserExpr(),  //用户公式
                        "timeExpr", task == null ? "--" : task.getTimeExpr(),  //时间公式
                        "actionExpr", task == null ? "--" : task.getActionExpr(),  //动作公式
                        "updater", "[" + (instanceTask.getUpdater() == null ? "--" : findNameById(instanceTask.getUpdater())) + "]" + (instanceTask.getUpdateDate() == null ? "--" : instanceTask.getUpdateDate()),
                        "creator", "[" + (instanceTask.getCreator() == null ? "--" : findNameById(instanceTask.getCreator())) + "]" + (instanceTask.getCreateDate() == null ? "--" : instanceTask.getCreateDate()),
                        "finished", instanceTask.isFinished() ? "1" : "0",
                        "fsmFlow", "[" + instanceTask.getFsmFlowInstance().getFsmFlow().getId() + "]" + instanceTask.getFsmFlowInstance().getFsmFlow().getName(),
                        "fsmState", "[" + instanceTask.getState().getId() + "]" + instanceTask.getState().getName()
                ));
            });
        }
        JSONArray objects = toJSONArray(temp);
        return MapUtil.mapper(
                "content", objects,
                "total", objects.size(),
                "size",  objects.size()
        );
    }

    /**
     * 查找名字
     * @param partyRoleId
     * @return 姓名
     */
    public String findNameById(String id){
        return SpringManager.getBean(DomainService.class).invoke("aut.user.findNameById", MapUtil.mapper(
                "id", id
        ));
    }

    /***
     * 功能： 用于处理返回值
     * @param lists
     * @return
     */
    protected JSONArray toJSONArray(List<Map> lists) {
        JSONArray returnArr = new JSONArray();
        lists.stream().forEach(list -> returnArr.add(new JSONObject(list)));
        return returnArr;
    }

    public StringBuffer formatExecuted(String s){
        StringBuffer reStr = new StringBuffer("");
        Map map = JSONObject.parseObject(s,Map.class);  //Json转map
        reStr.append("状态实例：" + map.get("状态实例") + "  用户：");
        Arrays.asList(map.get("用户").toString().replace("[","").replace("]","").replaceAll("\"","").split(",")).stream().forEach(str -> {
            reStr.append(findNameById(str) + "  ");
        });
        return reStr;
    }
}
